﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Maintenance.Util;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Maintenance
{
    public class PublicGlobal
    {
        public static readonly NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();

        public static FrmScreenProtect frmScreenProtect;

        public static MiniForm miniForm;

        public static bool autoOut;

        public static long TickCount { get; internal set; }

        public enum LogLevel
        {
            error = 1,
            info = 2,
            debug = 3,
        }

        public static bool IsProtectScreenShow()
        {
            if (frmScreenProtect == null)
            {
                return false;
            }
            else
            {
                return frmScreenProtect.Visible;
            }
        }

        public static void ShowScreenProtect(MiniForm miniForm,int rotationTime)
        {
            frmScreenProtect = new FrmScreenProtect(miniForm, rotationTime);
            frmScreenProtect.Show();
        }

        public static void HideScreenProtect()
        {
            if (frmScreenProtect != null && frmScreenProtect.Visible)
            {
                frmScreenProtect.Hide();
                frmScreenProtect.miniForm.StopMonitor();
                string lockWorkStation = "";
                try
                {
                    string data = "http://192.168.0.3:8888/application.json";
                    WebClient webpage = new WebClient();
                    var Json = webpage.DownloadString(data);
                    JObject json = (JObject)JsonConvert.DeserializeObject(Json);
                    if (json["lockWorkStation"].ToString() == ""|| json["lockWorkStation"].ToString() == null)
                    {
                        lockWorkStation = PublicGlobal.appConfigure.GetConfigureValue("Maintenance", "lockWorkStation", "true");
                    }
                    else
                    {
                        lockWorkStation = json["lockWorkStation"].ToString();
                    }
                }
                catch
                {
                    lockWorkStation = PublicGlobal.appConfigure.GetConfigureValue("Maintenance", "lockWorkStation", "true");
                };

                if (Boolean.Parse(lockWorkStation))
                {
                    LockWorkStation();
                }
                else {
                    frmScreenProtect.miniForm.StartMonitor();
                }
            }
        }

        [DllImport("user32.dll")]
        public static extern bool LockWorkStation();

        /// <summary>
        /// 系统配置
        /// </summary>
        public static AppConfigure appConfigure = null;

        /// <summary>
        /// 当前版本
        /// </summary>
        public static string currentVersion;

        /// <summary>
        /// 启动参数封装成启动对象
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        public static StartUpArgs GetStartUpArgs(string[] args)
        {
            StartUpArgs startUpArgs = null;
            if (args.Length > 0)
            {
                startUpArgs = new StartUpArgs();
                foreach (var arg in args)
                {
                    var argSplit = arg.Split(new Char[] { '=' });
                    if (argSplit.Length > 1)
                    {
                        if (argSplit[0].Trim().ToUpper() == "LOGINNAME")
                        {
                            startUpArgs.LOGINNAME = argSplit[1].Trim();
                        }
                        else if (argSplit[0].Trim().ToUpper() == "PASSWORD")
                        {
                            startUpArgs.PASSWORD = argSplit[1].Trim();
                        }
                        else if (argSplit[0].Trim().ToUpper() == "SYSID")
                        {
                            startUpArgs.SYSID = argSplit[1].Trim();
                        }
                    }
                }
            }
            return startUpArgs;
        }

        public static void StartUpdate()
        {
            string updateExe = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "EyFramework.AutoUpdate.exe");
            string processNmae = Process.GetCurrentProcess().ProcessName;
            Process.Start(updateExe, string.Format("ProcessName={0} startCmd={1}", processNmae, Application.ExecutablePath));
            Application.Exit();
        }

        /// <summary>
        /// 判断当前程序是否需要更新
        /// </summary>
        /// <returns></returns>
        public static bool CheckUpdate()
        {
            try
            {
                IniFileUtil iniFile = new IniFileUtil(Path.Combine(DirectoryUtil.GetCurrentDirectory(), "AutoUpdate.ini"));
                string currentVersion = iniFile.IniReadValue("AutoUpdate", "AppVersion", "0.0.0");
                PublicGlobal.currentVersion = currentVersion;
                string updateUrl = iniFile.IniReadValue("AutoUpdate", "UpdateUrl");
                if (!string.IsNullOrEmpty(updateUrl))
                {
                    VersionConfig versionConfig = GetCurrentVersion(updateUrl);
                    if (IsNewVersion(versionConfig.Version, currentVersion))
                    {
                        return true;
                    }
                }
                return false;
            }
            catch {
                return false;
            }
            
        }

        /// <summary>
        /// 比较第一个版本是否比第二个版本新
        /// 如果是返回true 否则返回false
        /// </summary>
        /// <param name="version1">第一个版本</param>
        /// <param name="version2">第二个版本</param>
        /// <returns></returns>
        public static bool IsNewVersion(string pNewVersion, string pOldVersion)
        {
            SysVersion oldV = new SysVersion(pOldVersion);
            SysVersion newV = new SysVersion(pNewVersion);
            if (newV.MajorVersionNumber > oldV.MajorVersionNumber)
            {
                return true;
            }
            else if (newV.MajorVersionNumber == oldV.MajorVersionNumber)
            {
                if (newV.MinorVersionNumber > oldV.MinorVersionNumber)
                {
                    return true;
                }
                else if (newV.MinorVersionNumber == oldV.MinorVersionNumber)
                {
                    if (newV.BuildNumber > oldV.BuildNumber)
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        public static VersionConfig GetCurrentVersion(string updateUrl)
        {
            string retString = string.Empty;
            //发起HTTP请求，获取当前服务器上的最新版本文件
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(updateUrl);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
            retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();
            if (response != null)
            {
                response.Close();
            }
            if (request != null)
            {
                request.Abort();
            }
            VersionConfig uv = JsonConvert.DeserializeObject<VersionConfig>(retString);
            return uv;
        }
    }
}